// pages/psi/analyse/dpfx/result/index.js
const app = getApp();
const wxCharts = app.require('utils/wxcharts.js'); // 这样引入

// pages/psi/sell/result/index.js
// var wxCharts = require('../../../../utils/wxcharts.js');
var lineChart = null;
var lineChart2 = null;

var pieChart = null;

const noData = [{
  name: '暂无数据',
  data: '1',
}, ];

const initFilters = {
  overall: 1,
  sorts: '',
  layout: 0,
};

// 折线图option
const optionLine = {
  canvasId: 'lineCanvas',
  type: 'line',
  categories: [],
  animation: true,
  background: '#f5f5f5',
  series: [{
    name: '日客单价',
    data: [],
    format: function (val, name) {
      return val + '';
    },
  }, ],
  xAxis: {
    disableGrid: true,
  },
  yAxis: {
    title: '近七天销售客单价走势',
    format: function (val) {
      return val.toFixed(0);
    },
    min: 0,
  },
  width: 320,
  height: 150,
  dataLabel: false,
  dataPointShape: true,
  extra: {
    lineStyle: 'curve',
  },
};
const optionLine2 = {
  canvasId: 'lineCanvas2',
  type: 'line',
  categories: [],
  animation: true,
  background: '#f5f5f5',
  series: [{
    name: '日销售数量',
    data: [],
    format: function (val, name) {
      return val + '';
    },
  }, ],
  xAxis: {
    disableGrid: true,
  },
  yAxis: {
    title: '近七天销售数量走势',
    format: function (val) {
      return val.toFixed(0);
    },
    min: 0,
  },
  width: 320,
  height: 150,
  dataLabel: false,
  dataPointShape: true,
  extra: {
    lineStyle: 'curve',
  },
};

// 饼图option
const optionPie = {
  animation: true,
  canvasId: 'pieCanvas',
  title: {
    name: '大类占比',
    fontSize: 12,
  },
  type: 'ring',
  series: [],
  width: 320,
  height: 300,
  dataLabel: true,
};

Page({
  /**
   * 页面的初始数据
   */
  data: {
    checkDist: 'data', // 单选框 
    goodsList: [],
    lineChartData: [],
    lineChartData2: [],
    barChartData: [],

    top5Data: [],
    userIdentity: '', // 用户身份
    dataList: [],

    sorts: '',
    overall: 1,
    show: false,
    minVal: '',
    maxVal: '',
    minSalePriceFocus: false,
    maxSalePriceFocus: false,
    filter: initFilters,
    hasLoaded: false,
    pageLoading: false,
    // 传参
    // 传参
    cityText: '',
    shopText: '',
    shop_code: '',
    day_begin: '',
    day_end: '',
    zx_status: '',
    yb_status: '',
    shop_attr: '',
    loading: true,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 检验是否登录
    app.checkLogin();
    // 获取身份权限
    this.setData({
      userIdentity: app.globalData.userIdentity
    });

    const {
      shop_code = '',
        day_begin = '',
        day_end = '',
        zx_status = '',
        yb_status = '',
        shop_attr = '',
    } = options || {};
    console.log('接收参数:');
    console.log(options);
    this.setData({
        shop_code,
        day_begin,
        day_end,
        zx_status,
        yb_status,
        shop_attr,
      },
      () => {
        this.init(true);
      },
    );
  },

  touchHandler: function (e) {
    console.log(lineChart.getCurrentDataIndex(e));
    lineChart.showToolTip(e, {
      // background: '#7cb5ec'
    });
  },
  touchHandler2: function (e) {
    console.log(lineChart2.getCurrentDataIndex(e));
    lineChart2.showToolTip(e, {
      // background: '#7cb5ec'
    });
  },
  touchHandler3: function (e) {
    console.log(pieChart.getCurrentDataIndex(e));
    pieChart.showToolTip(e, {
      // background: '#7cb5ec'
    });
  },
  onRadioChange(e) {
    this.setData({
      checkDist: e.detail.value
    });
    // 图表-单选框 
    this.getChart();
  },
  createSimulationData: function () {
    var categories = [];
    var data = [];

    // 判断是否携带数据
    const lineChartData = this.data.lineChartData;

    if (lineChartData && lineChartData.length > 0) {
      lineChartData.forEach((item) => {
        categories.push(item.name);
        data.push(item.data);
      });
    }

    var categories2 = [];
    var data2 = [];

    // 判断是否携带数据
    const lineChartData2 = this.data.lineChartData2;

    if (lineChartData2 && lineChartData2.length > 0) {
      lineChartData2.forEach((item) => {
        categories2.push(item.name);
        data2.push(item.data);
      });
    }


    // 单选框 
    const key = this.data.checkDist; // 'data' 或 'data2'

    // 1. 转数字并倒序
    const sorted = this.data.barChartData
      .map(item => ({
        ...item,
        num: Number(item[key] || 0)
      }))
      .sort((a, b) => b.num - a.num);

    // 2. 求和
    const sum = sorted.reduce((s, cur) => s + cur.num, 0);

    // 3. 加占比
    const dataList = sorted.map(item => ({
      ...item,
      rate: sum ? ((item.num / sum) * 100).toFixed(2) + '%' : '0.00%'
    }));
    this.setData({
      dataList: dataList,
    });

    return {
      categories: categories,
      data: data,
      categories2: categories2,
      data2: data2,
    };
  },

  //toHome() {
  getChart() {
    var windowWidth = 320;
    try {
      var res = wx.getSystemInfoSync();
      windowWidth = res.windowWidth;
    } catch (e) {
      console.error('getSystemInfoSync failed!');
    }

    var lineChartData = this.data.lineChartData;
    var lineChartData2 = this.data.lineChartData2;
    var top5Data = this.data.top5Data;
    var barChartData = this.data.barChartData; // table


    console.log('windowWidth:' + windowWidth);
    console.log('开始图表');

    // 生成图表data
    var simulationData = this.createSimulationData();

    optionLine.categories = simulationData.categories; // 数据类别分类 (饼图、圆环图不需要)
    optionLine.series[0].data = simulationData.data; // 数据
    optionLine.width = windowWidth - 20; // 宽带

    optionLine2.categories = simulationData.categories2; // 数据类别分类 (饼图、圆环图不需要)
    optionLine2.series[0].data = simulationData.data2; // 数据
    optionLine2.width = windowWidth - 20; // 宽带

    // 折线图
    console.log('lineChartData:' + lineChartData.length);
    if (lineChartData.length > 0) {
      lineChart = new wxCharts(optionLine);
    }

    if (lineChartData2.length > 0) {
      lineChart2 = new wxCharts(optionLine2);
    }

    // 饼图
    if (!top5Data) {
      top5Data = noData;
    }
    console.log(top5Data);
    optionPie.series = top5Data;
    optionPie.width = windowWidth;

    // pieChart = new wxCharts(optionPie);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},

  generalQueryData(reset = false) {
    const {
      filter,
      keywords,
      minVal,
      maxVal,
      cityText,
      shopText,
      shop_code,
      day_begin,
      day_end,
      zx_status,
      yb_status,
      shop_attr,
    } = this.data;
    const {
      pageNum,
      pageSize
    } = this;
    const {
      sorts,
      overall
    } = filter;
    const params = {
      sort: 0, // 0 综合，1 价格
      pageNum: 1,
      pageSize: 30,
      keyword: keywords,
    };

    if (sorts) {
      params.sort = 1;
      params.sortType = sorts === 'desc' ? 1 : 0;
    }
    if (overall) {
      params.sort = 0;
    } else {
      params.sort = 1;
    }
    // params.minPrice = minVal ? minVal * 100 : 0;
    // params.maxPrice = maxVal ? maxVal * 100 : undefined;

    params.cityText = cityText ? cityText : undefined;
    params.shopText = shopText ? shopText : undefined;

    params.shop_code = shop_code ? shop_code : '';
    params.day_begin = day_begin ? day_begin : '';
    params.day_end = day_end ? day_end : '';
    params.zx_status = zx_status ? zx_status : undefined;
    params.yb_status = yb_status ? yb_status : undefined;
    params.shop_attr = shop_attr ? shop_attr : undefined;

    if (reset) return params;
    return {
      ...params,
      pageNum: pageNum + 1,
      pageSize,
    };
  },

  getSearchResult(params, is_export) {
    console.log('getSearchResult');

    // const { shop_code, day_begin, day_end } = this.data;
    // console.log(shop_code);
    // console.log(day_begin);
    // console.log(day_end);
    const {
      userIdentity
    } = this.data;
    console.log('用户权限：' + userIdentity);

    return new Promise(function (resolve, reject) {
      wx.request({
        // url: 'http://localhost:4656/getDataJPFX.aspx', // 测试环境
        url: 'https://sst.jmit.cn/api_sst/getDataJPFX.aspx',
        //data: 'shop_code=' + this.data.shop_code + '&prd_code=' + this.data.prd_code,
        data: {
          ...params,
          is_export,
          user_identity: userIdentity, // 用户权限
        },
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
        },
        success: (request) => {
          console.log('getDataJPFX的结果', request.data);
          const res = request.data;
          //app.globalData.userInfo = res.data.data;//
          //var data = JSON.parse(res.data);

          resolve(res);
          // if (res.code == 200) {
          //   this.setData({ produces: res.data });
          // } else {
          // }
        },
        fail(res) {
          console.log(res);
          console.log('getDataJPFX的fail结果', res);
          reject(err);
        },
      });
    });
  },

  async init(reset = true) {
    const {
      loadMoreStatus,
      goodsList = []
    } = this.data;
    const params = this.generalQueryData(reset);
    //if (loadMoreStatus !== 0) return;
    console.log(1);

    this.setData({
      loadMoreStatus: 1,
      loading: true,
      pageLoading: true,
    });
    try {
      console.log('init');

      const result = await this.getSearchResult(params, false);

      // const result = {
      //   code: 200,
      //   data: [
      //     {
      //       ymd: '2023-11-30', // 日期
      //       shop_name: '', // 店铺名称
      //       kdj: '', // 客单价
      //       sell_amt: '', // 总金额
      //     },
      //     {
      //       ymd: '2023-11-30', // 日期
      //       shop_name: '', // 店铺名称
      //       kdj: '', // 客单价
      //       sell_amt: '', // 总金额
      //     },
      //   ],
      //   lineChartData: [
      //     {
      //       name: '2024-01-01', // 日期
      //       data: '10', // 客单价
      //     },
      //     {
      //       name: '2023-01-02',
      //       data: '15',
      //     },
      //     {
      //       name: '2023-01-03',
      //       data: '18',
      //     },
      //     {
      //       name: '2023-01-04',
      //       data: '14',
      //     },
      //     {
      //       name: '2023-01-05',
      //       data: '15',
      //     },
      //     {
      //       name: '2023-01-06',
      //       data: '12',
      //     },
      //     {
      //       name: '2023-01-07',
      //       data: '20',
      //     },
      //   ],
      //   top5Data: [
      //     {
      //       name: '大类1',
      //       data: 5,
      //     },
      //     {
      //       name: '大类2',
      //       data: 7,
      //     },
      //   ],
      //   msg: 'success',
      // };

      const code = result.code;
      const data = result.data;
      const lineChartData = result.lineChartData;
      const lineChartData2 = result.lineChartData2;
      const top5Data = result.pieChartData;
      const barChartData = result?.barChartData;

      console.log(4);
      console.log(lineChartData);
      console.log(lineChartData2);
      console.log(top5Data);
      console.log(barChartData);

      console.log(result);
      if (code === 200) {
        // const { spuList, totalCount = 0 } = data;

        // if (totalCount === 0 && reset) {
        //   this.total = totalCount;
        //   this.setData({
        //     emptyInfo: {
        //       tip: '抱歉，未找到相关商品',
        //     },
        //     hasLoaded: true,
        //     loadMoreStatus: 0,
        //     loading: false,
        //     goodsList: [],
        //   });
        //   return;
        // }

        const _lineChartData = lineChartData;
        const _lineChartData2 = lineChartData2;
        const _top5Data = top5Data;
        const _barChartData = barChartData;
        // _goodsList.forEach((v) => {
        //   v.tags = v.spuTagList.map((u) => u.title);
        //   v.hideKey = { desc: true };
        // });
        //const _loadMoreStatus = _goodsList.length === totalCount ? 2 : 0;
        //this.pageNum = params.pageNum || 1;
        //this.total = totalCount;

        this.setData({
          lineChartData: _lineChartData,
          lineChartData2: _lineChartData2,
          top5Data: _top5Data,
          barChartData: _barChartData,
          //loadMoreStatus: _loadMoreStatus,
        });
        // 图表
        this.getChart();

        // 操作日志记录
        app.api.log({
          title: '数据分析-竞品分析-查询',
          message: 'success',
        })

      } else {
        this.setData({
          loading: false,
        });
        wx.showToast({
          title: '未找到相关数据，请稍候重试',
        });

        // 操作日志记录
        app.api.log({
          title: '数据分析-竞品分析-查询',
          message: 'fail',
        })
      }
    } catch (error) {
      this.setData({
        loading: false,
      });
      console.log(error)
      // 操作日志记录
      app.api.log({
        title: '数据分析-竞品分析-查询',
        message: 'error',
      })
    }
    this.setData({
      hasLoaded: true,
      loading: false,
    });
  },

  // 导出
  submitExport() {
    this.getUrl();
    //this.downloadFile('https://sst.jmit.cn/api_sst/out/out_20231204050504.csv'); // 下载文件
  },
  async getUrl() {
    try {
      console.log('submitOrder');
      console.log('1');
      this.setData({
        downloadLink: '数据正在导出中，请稍等。。。',
      });

      const params = this.generalQueryData(true);
      console.log('2');

      const result = await this.getSearchResult(params, true);
      console.log('返回结果');
      console.log(result);

      const code = result.code;
      const outputUrl = result?.outputUrl;

      console.log('1111', outputUrl);
      if (code === 200) {
        // const { spuList, totalCount = 0 } = data;

        console.log('导出地址：', outputUrl);

        if (!outputUrl) {
          wx.showToast({
            title: '未找到相关数据，请稍候重试',
          });

          return;
        }

        // 操作日志记录
        app.api.log({
          title: '数据分析-竞品分析-导出',
          message: 'success',
        })

        wx.showToast({
          title: '数据已生成',
        });
        console.log('生成完成:' + outputUrl);
        this.setData({
          downloadLink: outputUrl,
        });

        //this.downloadFile(outputUrl); // 下载文件
      } else {
        this.setData({
          loading: false,
        });
        wx.showToast({
          title: '未找到相关数据，请稍候重试',
        });
      }
    } catch (error) {
      this.setData({
        loading: false,
      });
    }
  },
  async downloadFile(outUrl) {
    //const filePath = `${wx.env.USER_DATA_PATH}/out_20231204050317.csv`;
    var fileName = outUrl.substring(outUrl.lastIndexOf('/') + 1, outUrl.lastIndexOf('.'));
    //var fileName = outUrl.substring(outUrl.lastIndexOf('/') + 1);

    // fileName = 'out_20231204050317';
    // outUrl = 'https://sst.jmit.cn/api_sst/out/out_20231204050317.csv';

    console.log('outUrl:' + outUrl);
    console.log(outUrl.lastIndexOf('/') + 1);
    console.log('fileName:' + fileName);
    wx.downloadFile({
      url: outUrl,
      // 1. 必须带有这个wx.env.USER_DATA_PATH，表示存储在用户本地 ！！！
      // fileName表示自定的文件名称
      // 实际在PC端调试存储位置为类似 C:\Users\SJshe\AppData\Local\微信开发者工具\User Data\WeappFileSystem\o6zAJs3c0u3SeBVn_9MUgG6UZJ1M\wx2efdf4edd8bccb88
      filePath: wx.env.USER_DATA_PATH + '/' + fileName,
      success: function (res) {
        if (res.statusCode === 200) {
          // wx.showToast({
          //   title: '下载完成',
          // });
          // console.log('下载完成:' + res.filePath);
          // this.setData({
          //   downloadLink: res.filePath,
          // });
          // wx.openDocument({
          //   filePath: res.filePath,
          //   fileType: ['docx'], // 2. xlsx 这个必须写合法类型，不然下载不了(个人认为官方应该特别说明) ！！！
          //   success: function (res) {
          //     console.log('打开文档成功');
          //   },
          //   fail: function (e) {
          //     console.log('打开文档失败');
          //     console.log(e.errMsg);
          //   },
          // });
        }
      },
      fail: function (e) {
        // 强烈建议打印失败原因，便于排查
        console.log(e.errMsg);
      },
    });
  },
  copyText(e) {
    let key = e.currentTarget.dataset.key;
    wx.setClipboardData({
      //设置系统剪贴板的内容
      data: key,
      success(res) {
        console.log(res, key);
        wx.getClipboardData({
          // 获取系统剪贴板的内容
          success(res) {
            wx.showToast({
              title: '复制成功',
            });
          },
        });
      },
    });
  },
});